<template>
  <view class="team-records-page">
    <!-- 顶部导航栏 -->
    <tn-nav-bar
      fixed
      alpha
      backgroundColor="#020303"
      fontColor="#FFFFFF">
      <view slot="back" class="nav-back">
        <text class="tn-icon-left"></text>
      </view>
      <view class="nav-title">
        组队记录
      </view>
    </tn-nav-bar>
    
    <!-- 列表内容 -->
    <z-paging
      ref="paging"
      v-model="recordsList"
      @query="queryRecordsList"
      :default-page-size="10"
      :auto="true"
      :paging-style="{paddingTop: vuex_status_bar_height + 44 + 'px'}"
      :bg-color="'#020303'"
      :loading-more-enabled="true"
      :show-refresher-when-reload="true"
      :refresher-threshold="80"
      :refresher-default-text="'下拉刷新'"
      :refresher-pulling-text="'释放立即刷新'"
      :refresher-refreshing-text="'加载中...'"
      :loading-more-custom-style="{color: '#B3F73C'}"
      :show-loading-more-no-more-view="false"
      :hide-loading-more-when-no-more-and-inside-of-paging="true"
      :empty-view-text="'暂无组队记录'"
      :empty-view-reload-text="'点击刷新'"
      :show-empty-view-reload="true"
      :fixed="true"
      :safe-area-inset-bottom="true"
    >
      <!-- 组队记录列表 -->
      <view 
        v-for="(record, index) in recordsList" 
        :key="record.id"
        class="record-item"
      >
        <!-- 记录头部，包含时间和状态 -->
        <view class="record-header">
          <view class="record-time">
            <text class="tn-icon-time"></text>
            <text>{{ formatDate(record.joinTime) }}</text>
          </view>
          <view class="record-status">
            <text>{{ getStatusText(record.status) }}</text>
          </view>
        </view>
        
        <!-- 队长信息区域 -->
        <view class="team-header">
          <view class="team-creator">
            <image :src="record.avatar || defaultAvatar" class="creator-avatar" :class="{'male-border': record.gender === 1, 'female-border': record.gender !== 1}" mode="aspectFill"></image>
            <view class="creator-info">
              <view class="creator-name">
                {{ record.nickname || '未知用户' }}
                <text :class="['gender-icon', record.gender === 1 ? 'male' : 'female']">
                  <text v-if="record.gender === 1" class="tn-icon-sex-male"></text>
                  <text v-else class="tn-icon-sex-female"></text>
                </text>
              </view>
              <view class="creator-rank">
                <view class="rank-badge">{{ getRankName(record.rankLevel) }}</view>
                <view class="server-badge">{{ record.areaType === 1 ? '微信区' : 'QQ区' }}</view>
                <view class="team-type-badge">
                  {{ getTeamTypeName(record.teamType) }}
                </view>
              </view>
              <view class="creator-success-count">
                <text class="tn-icon-flag"></text>
                <text>成功组队: {{ record.successCount || 0 }}次</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 队伍信息 -->
        <view class="team-info">
          <view class="team-title">{{ record.title }}</view>
          <view class="team-desc">{{ record.description }}</view>

          <view class="team-details">
            <view class="team-detail">
              <text class="tn-icon-time"></text>
              <text>{{ formatDate(record.createTime) }}</text>
            </view>
            <view class="team-detail">
              <text class="tn-icon-people"></text>
              <text>{{ record.members ? record.members.length : 0 }}/5</text>
            </view>
            <view class="team-detail">
              <text class="tn-icon-location"></text>
              <text>{{ record.location || '未知' }}</text>
            </view>
          </view>
        </view>
        
        <!-- 成员位置显示 -->
        <view class="team-members">
          <view class="team-member" v-for="(member, mIndex) in record.members" :key="mIndex" :class="{'current-user': member.isCurrentUser}">
            <image :src="member.avatar || defaultAvatar" class="member-avatar" :class="{'male-border': member.sex === 1, 'female-border': member.sex !== 1}" mode="aspectFill"></image>
            <view class="member-position">{{ getPositionName(member.position) }}</view>
            <!-- 当前用户标记 -->
            <view class="current-user-badge" v-if="member.isCurrentUser">
              <text>我</text>
            </view>
            <!-- 当前用户是队长且组队完成时，显示拉黑选项 -->
            <view class="member-actions" v-if="isCurrentUserCreator(record) && record.status === 2 && record.userId !== member.userId">
              <view class="member-action blacklist" @tap.stop="toggleBlacklist(record, member)">
                <text :class="member.isBlacklisted ? 'tn-icon-block' : 'tn-icon-prohibit'"></text>
                <text>{{ member.isBlacklisted ? '取消' : '拉黑' }}</text>
              </view>
            </view>
          </view>
          <view
            v-for="i in (5 - (record.members ? record.members.length : 0))"
            :key="i"
            class="team-member empty"
          >
            <text class="tn-icon-add"></text>
          </view>
        </view>
        
        <!-- 游戏ID和联系方式信息面板 -->
        <view class="game-id-panel" v-if="record.members && record.members.length > 0">
          <view class="panel-header">
            <text class="panel-title">游戏ID 与 联系方式</text>
            <view class="lock-status" v-if="!record.canDecrypt">
              <text class="tn-icon-lock"></text>
              <text v-if="record.joinedByCurrentUser">凑齐5人开黑后解锁</text>
              <text v-else-if="!record.joinedByCurrentUser && record.isTeamFull">队伍已满，仅成员可见</text>
              <text v-else>仅队伍成员可见</text>
            </view>
            <!-- 解锁状态不显示任何内容，界面更简洁 -->
          </view>

          <view class="game-ids-list">
            <view
              class="game-id-item"
              v-for="(member, index) in record.members"
              :key="index"
              :class="{'locked': !record.canDecrypt, 'current-user': member.isCurrentUser}"
            >
              <view class="id-position">
                {{ getPositionName(member.position) }}
              </view>
              <view class="id-value">
                <template v-if="record.canDecrypt">
                  <view class="id-row">
                    <text class="id-label">ID:</text>
                    <text>{{ member.gameId }}</text>
                  </view>
                  <view class="id-row">
                    <text class="id-label">{{ record.areaType === 1 ? '微信' : 'QQ' }}:</text>
                    <text>{{ member.contact }}</text>
                  </view>
                </template>
                <template v-else>••••••••</template>
              </view>
              <view class="id-actions" v-if="record.canDecrypt">
                <view class="id-copy" @tap="copyGameId(member.gameId)">
                  <text class="tn-icon-copy"></text>
                  <text class="copy-label">复制ID</text>
                </view>
                <view class="id-copy" @tap="copyContact(member.contact)">
                  <text class="tn-icon-copy"></text>
                  <text class="copy-label">复制{{ record.areaType === 1 ? '微信' : 'QQ' }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 邀请提示 - 仅显示给队伍未满的记录 -->
        <view
          class="invite-tip"
          v-if="record.status === 0 && record.members && record.members.length < 5 && record.members.length >= 3"
        >
          <text class="tn-icon-info"></text>
          <text>再邀请{{5 - record.members.length}}人即可解锁游戏ID和联系方式</text>
        </view>
        
        <!-- 组队操作按钮 -->
        <view class="team-actions">
          <button
            class="action-btn join-btn"
            :class="{
              'full': record.members && record.members.length >= 5,
              'joined': record.joinedByCurrentUser
            }"
            :disabled="(record.members && record.members.length >= 5) && !record.joinedByCurrentUser"
            @tap="toggleJoinTeam(record)"
            v-if="record.status === 0 && !(record.members && record.members.length >= 5 && record.joinedByCurrentUser)"
          >
            <text v-if="record.joinedByCurrentUser">退出队伍</text>
            <text v-else>{{ (record.members && record.members.length >= 5) ? '已满员' : '加入' }}</text>
          </button>
          <!-- #ifdef MP-WEIXIN -->
          <button
            class="action-btn invite-btn"
            v-if="record.status === 0 && record.members && record.members.length < 5"
            open-type="share"
            @tap="prepareShare(record)"
          >
            <text class="tn-icon-share"></text>
            邀请好友
          </button>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <button
            class="action-btn invite-btn"
            v-if="record.status === 0 && record.members && record.members.length < 5"
            @tap="showInviteModal(record)"
          >
            <text class="tn-icon-share"></text>
            邀请好友
          </button>
          <!-- #endif -->
        </view>
        
        <!-- 排位截图上传区域 -->
        <view class="record-action" v-if="isCurrentUserCreator(record) && record.status === 2 && (!record.rankScreenshot || record.rankResult === 0)">
          <!-- 添加上传截图重要性提示 -->
          <view class="upload-tip">
            <text class="tn-icon-info"></text>
            <text class="tip-text">作为队长，请上传排位赛截图记录本次组队成果！</text>
          </view>

          <view class="action-title">
            <view class="title-left">
              <text class="tn-icon-upload"></text>
              <text>上传排位截图</text>
            </view>
            <!-- 审核中状态显示 -->
            <view v-if="record.rankScreenshot && record.rankResult === 0" class="audit-status">
              <text class="audit-text">审核中</text>
            </view>
          </view>

          <view class="upload-area">
            <!-- 已上传的截图显示（可点击预览） -->
            <image v-if="record.uploadedRankScreenshot || record.rankScreenshot"
                   :src="record.uploadedRankScreenshot || record.rankScreenshot"
                   class="screenshot"
                   mode="aspectFill"
                   @tap="previewScreenshot(record.uploadedRankScreenshot || record.rankScreenshot)"></image>
            <!-- 未上传时的选择区域（可点击） -->
            <view v-else class="upload-placeholder" @tap="chooseRankScreenshot(record.id)">
              <text class="tn-icon-add"></text>
              <text>选择排位截图</text>
            </view>

            <!-- 上传进度 -->
            <view v-if="record.uploading" class="upload-progress">
              <view class="progress-bar">
                <view class="progress-fill" :style="{width: record.uploadProgress + '%'}"></view>
              </view>
              <text class="progress-text">{{ record.uploadProgress }}%</text>
            </view>
          </view>

          <!-- 按钮区域 -->
          <view class="button-area">
            <!-- 首次上传：只显示提交按钮 -->
            <template v-if="!record.rankScreenshot">
              <button
                class="submit-btn single-btn"
                :disabled="!record.uploadedRankScreenshot || record.uploading"
                @tap="submitRankScreenshot(record.id)"
              >{{ record.uploadedRankScreenshot ? '提交截图' : '请先上传截图' }}</button>
            </template>

            <!-- 审核中状态：显示两个按钮 -->
            <template v-else-if="record.rankResult === 0">
              <button
                class="reupload-btn"
                :disabled="record.uploading"
                @tap="chooseRankScreenshot(record.id)"
              >重新上传</button>

              <button
                class="submit-btn"
                :disabled="record.uploading"
                @tap="submitRankScreenshot(record.id)"
              >{{ record.uploadedRankScreenshot ? '提交截图' : '重新提交' }}</button>
            </template>
          </view>
        </view>
        
        <!-- 队伍成员提示队长上传截图 -->
        <view class="member-upload-tip" v-if="!isCurrentUserCreator(record) && record.status === 2 && !record.rankScreenshot">
          <view class="tip-content">
            <text class="tn-icon-info"></text>
            <text class="tip-text">组队已完成，等待队长上传排位截图记录战绩</text>
          </view>
        </view>

        <!-- 已上传排位截图状态显示 -->
        <view class="record-rated" v-if="record.rankScreenshot && (!isCurrentUserCreator(record) || record.rankResult !== 0)">
          <view class="rated-title">
            <text>排位截图</text>
            <view class="rank-result">
              <text class="result-text" :class="record.rankResult === 1 ? 'win' : (record.rankResult === 2 ? 'lose' : 'audit')">
                {{ record.rankResult === 1 ? '胜利' : (record.rankResult === 2 ? '失败' : '审核中') }}
              </text>
            </view>
          </view>
          <view class="rated-content">
            <view class="rated-screenshot">
              <image :src="record.rankScreenshot" class="screenshot" mode="aspectFill" @tap="previewScreenshot(record.rankScreenshot)"></image>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script>
/**
 * 组队记录页面
 * 用于查看用户历史组队记录，上传排位截图和评分
 */
import { getMyJoinTeamPage, leaveGameKingTeam, uploadRankScreenshot, addBlacklist, removeBlacklist } from '@/api/game/index.js';
import { uploadFile } from '@/api/upload/index.js';
import { getRankNameById } from '@/utils/constants.js';
import config from '@/config/index.js';

export default {
  // #ifdef MP-WEIXIN
  onShareAppMessage(res) {
    // 如果是从按钮触发的分享
    if (res.from === 'button') {
      return {
        title: this.shareConfig.title,
        path: this.shareConfig.path,
        imageUrl: this.shareConfig.imageUrl
      };
    }

    // 默认分享
    return {
      title: "王者荣耀开黑组队，一起上分！",
      path: '/pages/team/index',
      imageUrl: ''
    };
  },
  // #endif

  data() {
    return {
      recordsList: [],
      vuex_status_bar_height: uni.getSystemInfoSync().statusBarHeight,
      // 添加游戏位置映射
      positions: [
        { id: 1, name: '上单' },
        { id: 2, name: '打野' },
        { id: 3, name: '中单' },
        { id: 4, name: '射手' },
        { id: 5, name: '辅助' }
      ],
      // 默认头像
      defaultAvatar: 'https://rbtnet.oss-cn-hangzhou.aliyuncs.com/f58cad729ce47acb65666e57496f5e2e0c8badfec8355cfc7d6f2645f8738e60.jpeg',

      // 分享配置
      shareConfig: {
        title: '',
        path: '',
        imageUrl: '',
        record: null
      }
    }
  },
  methods: {
    /**
     * 获取组队记录列表
     * @param {Object} pageNo - 页码
     * @param {Object} pageSize - 每页数量
     */
    queryRecordsList(pageNo, pageSize) {
      // 调用API获取数据
      getMyJoinTeamPage({
        pageNo,
        pageSize
      }).then(res => {
        this.$refs.paging.complete(res.list);
      }).catch(err => {
        console.error('获取组队记录失败:', err);
        this.$refs.paging.complete(false);
      });
    },
    
    /**
     * 格式化日期
     * @param {String} dateString - ISO格式日期字符串
     * @returns {String} 格式化的时间字符串
     */
    formatDate(dateString) {
      if (!dateString) return '';
      
      const date = new Date(dateString);
      return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes() < 10 ? '0' : ''}${date.getMinutes()}`;
    },
    
    /**
     * 获取状态显示文本
     * @param {Number} status - 状态标识
     * @returns {String} 显示文本
     */
    getStatusText(status) {
      const statusMap = {
        0: '组队中',
        1: '已取消',
        2: '已完成'
      };
      return statusMap[status] || '未知状态';
    },
    
    /**
     * 获取段位名称
     * @param {Number} rankLevel - 段位级别
     * @returns {String} 段位名称
     */
    getRankName(rankLevel) {
      return getRankNameById(rankLevel);
    },
    
    /**
     * 获取队伍类型名称
     * @param {Number} teamType - 队伍类型
     * @returns {String} 队伍类型名称
     */
    getTeamTypeName(teamType) {
      const typeMap = {
        1: '娱乐局',
        2: '排位赛',
        3: '找对象'
      };
      return typeMap[teamType] || '未知类型';
    },
    
    /**
     * 获取位置名称
     * @param {Number} positionId - 位置ID
     * @returns {String} 位置名称
     */
    getPositionName(positionId) {
      const position = this.positions.find(p => p.id === positionId);
      return position ? position.name : '未知位置';
    },
    
    /**
     * 判断当前用户是否为创建者
     * @param {Object} record - 记录对象
     * @returns {Boolean} 是否为创建者
     */
    isCurrentUserCreator(record) {
      // 优先从store获取当前用户ID，如果没有则从本地存储获取
      const currentUserId = this.$store.state.user.userInfo?.id || uni.getStorageSync('userId');
      return record.userId === currentUserId;
    },
    
    /**
     * 复制游戏ID
     * @param {String} gameId - 游戏ID
     */
    copyGameId(gameId) {
      uni.setClipboardData({
        data: gameId,
        success: () => {
          uni.showToast({
            title: '游戏ID已复制',
            icon: 'success'
          });
        }
      });
    },
    
    /**
     * 复制联系方式
     * @param {String} contactNumber - 联系方式
     */
    copyContact(contactNumber) {
      uni.setClipboardData({
        data: contactNumber,
        success: () => {
          uni.showToast({
            title: '联系方式已复制',
            icon: 'success'
          });
        }
      });
    },
    
    /**
     * 退出队伍
     * @param {Number} recordId - 记录ID
     */
    exitTeam(recordId) {
      uni.showModal({
        title: '提示',
        content: '确定要退出该队伍吗？',
        success: (res) => {
          if (res.confirm) {
            // TODO: 实现退出队伍API调用
            uni.showLoading({
              title: '退出中...'
            });
            
            // 模拟网络延迟
            setTimeout(() => {
              // 将记录状态更新为已取消
              const recordIndex = this.recordsList.findIndex(item => item.id === recordId);
              if (recordIndex !== -1) {
                this.recordsList[recordIndex].status = 1;
              }
              
              uni.hideLoading();
              uni.showToast({
                title: '已退出队伍',
                icon: 'success'
              });
            }, 500);
          }
        }
      });
    },
    
    /**
     * 准备分享（微信小程序环境）
     * @param {Object} record - 记录对象
     */
    prepareShare(record) {
      // 设置分享配置
      this.shareConfig.record = record;
      this.shareConfig.title = `${record.creatorName}邀请你一起开黑！`;
      this.shareConfig.path = `/pages/team/detail?id=${record.id}`;
      this.shareConfig.imageUrl = ''; // 使用默认截图

      console.log('准备分享队伍:', record.id);
    },

    /**
     * 显示邀请弹窗（非微信环境）
     * @param {Object} record - 记录对象
     */
    showInviteModal(record) {
      uni.showActionSheet({
        itemList: ['复制邀请链接'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.copyInviteLink(record);
          }
        }
      });
    },

    /**
     * 复制邀请链接
     * @param {Object} record - 记录对象
     */
    copyInviteLink(record) {
      // 构建H5邀请链接
      const h5InviteUrl = `${config.h5URL}/#/pages/team/detail?id=${record.id}`;

      const inviteText = `${record.creatorName}邀请你加入王者荣耀队伍！\n\n队伍信息：\n人数：${record.members ? record.members.length : 0}/5\n开黑时间：${record.startTime}\n服务器：${record.areaType === 1 ? '微信区' : 'QQ区'}\n\n点击链接加入：${h5InviteUrl}`;

      uni.setClipboardData({
        data: inviteText,
        success: () => {
          uni.showToast({
            title: '邀请信息已复制',
            icon: 'success',
            duration: 2000
          });
        },
        fail: () => {
          uni.showToast({
            title: '复制失败',
            icon: 'none'
          });
        }
      });
    },

    /**
     * 邀请好友加入队伍（保留原方法，用于兼容）
     * @param {Object} record - 记录对象
     */
    inviteFriends(record) {
      this.showInviteModal(record);
    },
    
    /**
     * 选择排位截图并立即上传
     * @param {Number} recordId - 记录ID
     */
    async chooseRankScreenshot(recordId) {
      try {
        const res = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: resolve,
            fail: reject
          });
        });

        const recordIndex = this.recordsList.findIndex(item => item.id === recordId);
        if (recordIndex === -1) return;

        const record = this.recordsList[recordIndex];
        const filePath = res.tempFilePaths[0];

        // 如果是重新上传，清理之前的上传结果
        if (record.uploadedRankScreenshot) {
          delete record.uploadedRankScreenshot;
        }

        // 设置上传状态
        this.$set(record, 'uploading', true);
        this.$set(record, 'uploadProgress', 0);

        // 立即上传图片
        const uploadResult = await uploadFile({
          filePath: filePath,
          fileType: 'game',
          onProgress: (progress) => {
            this.$set(record, 'uploadProgress', progress);
          }
        });

        // 上传成功，保存URL
        this.$set(record, 'uploadedRankScreenshot', uploadResult);
        this.$set(record, 'uploading', false);

        uni.showToast({
          title: '图片上传成功',
          icon: 'success'
        });

      } catch (error) {
        const recordIndex = this.recordsList.findIndex(item => item.id === recordId);
        if (recordIndex !== -1) {
          this.$set(this.recordsList[recordIndex], 'uploading', false);
        }

        if (!error.errMsg || !error.errMsg.includes('cancel')) {
          uni.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
        }
      }
    },
    
    /**
     * 提交排位截图
     * @param {Number} recordId - 记录ID
     */
    async submitRankScreenshot(recordId) {
      const recordIndex = this.recordsList.findIndex(item => item.id === recordId);
      if (recordIndex === -1) return;

      const record = this.recordsList[recordIndex];
      if (!record.uploadedRankScreenshot) {
        uni.showToast({
          title: '请先上传排位截图',
          icon: 'none'
        });
        return;
      }

      // 显示提交中
      uni.showLoading({
        title: '提交中...'
      });

      try {
        // 调用后端API提交排位截图URL
        await uploadRankScreenshot({
          teamId: record.id,
          rankScreenshot: record.uploadedRankScreenshot
        });

        // 更新记录状态
        this.recordsList[recordIndex].rankScreenshot = record.uploadedRankScreenshot;
        this.recordsList[recordIndex].rankResult = 0; // 默认为未知，等待审核

        // 清理临时数据
        delete this.recordsList[recordIndex].uploadedRankScreenshot;

        uni.hideLoading();
        uni.showToast({
          title: '截图提交成功',
          icon: 'success'
        });
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        });
      }
    },

    /**
     * 预览排位截图
     * @param {String} imageUrl - 图片URL
     */
    previewScreenshot(imageUrl) {
      if (imageUrl) {
        uni.previewImage({
          urls: [imageUrl],
          current: imageUrl
        });
      }
    },

    /**
     * 切换加入队伍状态
     * @param {Object} record - 记录对象
     */
    toggleJoinTeam(record) {
      if (record.joinedByCurrentUser) {
        // 如果已加入，则退出
        uni.showModal({
          title: '提示',
          content: '确定要退出该队伍吗？',
          success: async (res) => {
            if (res.confirm) {
              // 显示加载中
              uni.showLoading({
                title: '退出中...',
                mask: true
              });
              
              try {
                // 找到当前用户的成员ID
                const currentUserId = this.$store.state.user.userInfo?.id || uni.getStorageSync('userId');
                const currentMember = record.members.find(member => member.userId == currentUserId);
                
                if (!currentMember || !currentMember.id) {
                  throw new Error('未找到您在该队伍中的信息');
                }
                
                // 记录成员ID用于后续更新
                const memberId = currentMember.id;
                
                // 调用后端接口退出队伍
                await leaveGameKingTeam(memberId);
                
                // 关闭加载提示
                uni.hideLoading();
                
                // 显示退出成功提示
                uni.showToast({
                  title: '已退出队伍',
                  icon: 'success'
                });
                
                // 在内存中更新队伍数据
                this.updateTeamAfterLeave(record);
              } catch (error) {
                uni.hideLoading();
                console.error('退出队伍失败:', error);
                uni.showToast({
                  title: error.msg || error.message || '退出队伍失败，请稍后重试',
                  icon: 'none'
                });
              }
            }
          }
        });
      } else {
        // 如果未加入，则加入
        if (record.members && record.members.length >= 5) {
          uni.showToast({
            title: '队伍已满',
            icon: 'none'
          });
          return;
        }
        
        uni.showModal({
          title: '提示',
          content: '确定要加入该队伍吗？',
          success: (res) => {
            if (res.confirm) {
              // TODO: 实现加入队伍API调用
              uni.showLoading({
                title: '加入中...'
              });
              
              // 模拟网络延迟
              setTimeout(() => {
                // 将记录状态更新
                const recordIndex = this.recordsList.findIndex(item => item.id === record.id);
                if (recordIndex !== -1) {
                  this.recordsList[recordIndex].joinedByCurrentUser = true;
                  
                  // 如果加入后队伍满员，则解锁联系方式
                  if (this.recordsList[recordIndex].members.length >= 4) { // 加入后会是5人
                    this.recordsList[recordIndex].canDecrypt = true;
                  }
                }
                
                uni.hideLoading();
                uni.showToast({
                  title: '已加入队伍',
                  icon: 'success'
                });
              }, 500);
            }
          }
        });
      }
    },
    
    /**
     * 切换黑名单状态
     * @param {Object} record - 记录对象
     * @param {Object} member - 成员对象
     */
    async toggleBlacklist(record, member) {
      try {
        const isCurrentlyBlacklisted = member.isBlacklisted;
        const action = isCurrentlyBlacklisted ? '取消拉黑' : '拉黑';

        // 确认操作
        const confirmResult = await new Promise((resolve) => {
          uni.showModal({
            title: '确认操作',
            content: `确定要${action}该成员吗？`,
            success: (res) => resolve(res.confirm)
          });
        });

        if (!confirmResult) return;

        // 调用后端API
        if (isCurrentlyBlacklisted) {
          // 取消拉黑
          await removeBlacklist({
            blacklistedUserId: member.userId
          });
        } else {
          // 拉黑
          await addBlacklist({
            blacklistedUserId: member.userId,
            reason: '组队违规行为'
          });
        }

        // 更新本地状态
        member.isBlacklisted = !isCurrentlyBlacklisted;

        uni.showToast({
          title: `${action}成功`,
          icon: 'success'
        });
      } catch (error) {
        console.error('拉黑操作失败:', error);
        uni.showToast({
          title: error.msg || error.message || '操作失败',
          icon: 'error'
        });
      }
    },
    
    /**
     * 退出队伍后从记录列表中移除该组队
     * @param {Object} record - 记录对象
     */
    updateTeamAfterLeave(record) {
      // 在当前记录列表中找到要更新的记录的索引
      const recordIndex = this.recordsList.findIndex(item => item.id === record.id);
      if (recordIndex === -1) return;
      
      // 直接从记录列表中移除该组队
      this.recordsList.splice(recordIndex, 1);
      
      // 通知z-paging组件数据发生了变化
      this.$nextTick(() => {
        if (this.$refs.paging) {
          this.$refs.paging.updateCache();
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.team-records-page {
  min-height: 100vh;
  background-color: #020303;
  padding-bottom: 30rpx;
}

// 导航栏样式
.nav-title {
  color: #FFFFFF;
  font-size: 36rpx;
  font-weight: bold;
}

.nav-back {
  color: #FFFFFF;
  font-size: 36rpx;
}

// 记录条目样式
.record-item {
  background-color: rgba(17, 17, 17, 0.8);
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
  }
  
  .record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .record-time {
      display: flex;
      align-items: center;
      color: rgba(255, 255, 255, 0.6);
      font-size: 24rpx;
      
      .tn-icon-time {
        margin-right: 6rpx;
      }
    }
    
    .record-status {
      font-size: 24rpx;
      color: #B3F73C;
      padding: 5rpx 15rpx;
      background-color: rgba(179, 247, 60, 0.1);
      border-radius: 20rpx;
    }
  }
  
  .team-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .team-creator {
      display: flex;
      align-items: center;
      
      .creator-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 16rpx;
        border: 2rpx solid #B3F73C;
        
        &.male-border {
          border: 3rpx solid #0088FF; /* 男性用蓝色边框 */
        }
        
        &.female-border {
          border: 3rpx solid #FF6699; /* 女性用粉色边框 */
        }
      }
      
      .creator-info {
        display: flex;
        flex-direction: column;
        
        .creator-name {
          color: #FFFFFF;
          font-size: 28rpx;
          font-weight: bold;
          display: flex;
          align-items: center;
          
          .gender-icon {
            margin-left: 10rpx;
            font-size: 24rpx;
            
            &.male {
              color: #0088FF;
            }
            
            &.female {
              color: #FF6699;
            }
          }
        }
        
        .creator-rank {
          margin-top: 6rpx;
          display: flex;
          align-items: center;
          
          .rank-badge {
            display: inline-block;
            padding: 4rpx 12rpx;
            border-radius: 20rpx;
            background-color: rgba(179, 247, 60, 0.2);
            color: #B3F73C;
            font-size: 22rpx;
            margin-right: 10rpx;
          }
          
          .server-badge {
            display: inline-block;
            padding: 4rpx 12rpx;
            border-radius: 20rpx;
            background-color: rgba(179, 247, 60, 0.2);
            color: #B3F73C;
            font-size: 22rpx;
          }
          
          .team-type-badge {
            display: inline-block;
            padding: 4rpx 12rpx;
            border-radius: 20rpx;
            background-color: rgba(179, 247, 60, 0.2);
            color: #B3F73C;
            font-size: 22rpx;
            margin-left: 10rpx;
          }
        }
        
        .creator-success-count {
          display: flex;
          align-items: center;
          margin-top: 6rpx;
          
          .tn-icon-flag {
            color: #B3F73C;
            font-size: 24rpx;
            margin-right: 6rpx;
          }
          
          text {
            color: rgba(255, 255, 255, 0.9);
            font-size: 22rpx;
          }
        }
      }
    }
  }
  
  .team-info {
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    
    .team-title {
      color: #FFFFFF;
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .team-desc {
      color: rgba(255, 255, 255, 0.6);
      font-size: 24rpx;
      margin-bottom: 10rpx;
    }

    .team-details {
      display: flex;
      justify-content: space-between;
      margin-top: 16rpx;
      
      .team-detail {
        display: flex;
        align-items: center;
        
        .tn-icon-time, .tn-icon-people, .tn-icon-location {
          color: #B3F73C;
          font-size: 24rpx;
          margin-right: 6rpx;
        }
        
        text {
          color: rgba(255, 255, 255, 0.9);
          font-size: 22rpx;
        }
      }
    }
  }
  
  .team-members {
    display: flex;
    margin-bottom: 20rpx;
    overflow-x: auto;
    padding: 10rpx 0;
    
    &::-webkit-scrollbar {
      display: none;
    }
    
    .team-member {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 20rpx;
      min-width: 80rpx;
      
      .member-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        border: 2rpx solid #B3F73C; /* 默认边框 */
        
        &.male-border {
          border: 3rpx solid #0088FF; /* 男性用蓝色边框 */
        }
        
        &.female-border {
          border: 3rpx solid #FF6699; /* 女性用粉色边框 */
        }
      }
      
      .member-position {
        color: rgba(255, 255, 255, 0.6);
        font-size: 22rpx;
        margin-top: 6rpx;
      }

      /* 当前用户标记 */
      .current-user-badge {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        background: #B3F73C;
        color: #000000;
        font-size: 20rpx;
        font-weight: bold;
        width: 32rpx;
        height: 32rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2rpx solid #020303;
      }

      /* 当前用户成员容器样式 */
      &.current-user {
        position: relative;

        .member-avatar {
          border: 3rpx solid #B3F73C !important;
        }
      }
      
      .member-actions {
        display: flex;
        justify-content: space-between;
        margin-top: 6rpx;
        
        .member-action {
          display: flex;
          align-items: center;
          padding: 4rpx 10rpx;
          border-radius: 6rpx;
          background-color: rgba(179, 247, 60, 0.1);
          color: #B3F73C;
          font-size: 22rpx;
          
          &.blacklist {
            margin-right: 10rpx;
          }
        }
      }
    }
    
    .empty {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      border: 2rpx dashed rgba(255, 255, 255, 0.3);
      margin-right: 20rpx;
      
      .tn-icon-add {
        color: rgba(255, 255, 255, 0.3);
        font-size: 40rpx;
      }
    }
  }
  
  .game-id-panel {
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    
    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;
      
      .panel-title {
        color: #FFFFFF;
        font-size: 26rpx;
        font-weight: bold;
      }
      
      .lock-status {
        display: flex;
        align-items: center;
        color: rgba(255, 255, 255, 0.6);
        font-size: 22rpx;
        
        .tn-icon-lock {
          color: #FF6B6B;
          font-size: 24rpx;
          margin-right: 6rpx;
        }
      }
      
      .lock-status.unlocked {
        color: #B3F73C;

        .tn-icon-unlock {
          color: #B3F73C;
          font-size: 24rpx;
        }
      }
    }
    
    .game-ids-list {
      .game-id-item {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
        padding: 10rpx;
        border-radius: 8rpx;
        background-color: rgba(0, 0, 0, 0.2);
        
        &.locked {
          background-color: rgba(0, 0, 0, 0.1);
        }

        &.current-user {
          background-color: rgba(179, 247, 60, 0.1);
          border: 2rpx solid rgba(179, 247, 60, 0.3);
        }

        .id-position {
          color: rgba(255, 255, 255, 0.6);
          font-size: 24rpx;
          margin-right: 10rpx;
          width: 60rpx;
        }
        
        .id-value {
          color: #FFFFFF;
          font-size: 24rpx;
          flex: 1;
          
          .id-row {
            display: flex;
            align-items: center;
            margin-bottom: 4rpx;
            
            &:last-child {
              margin-bottom: 0;
            }
          }
          
          .id-label {
            color: #B3F73C;
            font-size: 22rpx;
            margin-right: 8rpx;
            width: 60rpx;
          }
        }
        
        .id-actions {
          display: flex;
          flex-direction: column;
          margin-left: 10rpx;
        }
        
        .id-copy {
          color: #B3F73C;
          font-size: 24rpx;
          padding: 8rpx 10rpx;
          display: flex;
          align-items: center;
          background-color: rgba(179, 247, 60, 0.1);
          border-radius: 6rpx;
          margin-bottom: 8rpx;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .copy-label {
            font-size: 20rpx;
            margin-left: 6rpx;
          }
        }
      }
    }
  }
  
  .invite-tip {
    display: flex;
    align-items: center;
    padding: 16rpx 20rpx;
    background-color: rgba(179, 247, 60, 0.1);
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    
    .tn-icon-info {
      color: #B3F73C;
      font-size: 28rpx;
      margin-right: 10rpx;
    }
    
    text {
      color: #B3F73C;
      font-size: 24rpx;
    }
  }
  
  .team-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
    
    .action-btn {
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 35rpx;
      font-size: 26rpx;
      font-weight: bold;
      flex: 1;
      
      &.join-btn {
        background-color: rgba(179, 247, 60, 0.2);
        color: #B3F73C;
        margin-right: 10rpx;
        
        &.joined {
          background-color: rgba(255, 107, 107, 0.2);
          color: #FF6B6B;
        }
        
        &.full {
          background-color: rgba(128, 128, 128, 0.2);
          color: rgba(255, 255, 255, 0.5);
        }
      }
      
      &.invite-btn {
        background-color: rgba(179, 247, 60, 0.2);
        color: #B3F73C;
        margin-left: 10rpx;
        
        .tn-icon-share {
          margin-right: 6rpx;
        }
      }
    }
  }
  
  .record-action {
    background: linear-gradient(135deg, rgba(179, 247, 60, 0.1) 0%, rgba(0, 0, 0, 0.3) 100%);
    border: 1px solid rgba(179, 247, 60, 0.2);
    border-radius: 16rpx;
    padding: 24rpx;
    margin-top: 20rpx;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 2rpx;
      background: linear-gradient(90deg, transparent, #B3F73C, transparent);
    }

    .upload-tip {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      padding: 15rpx;
      background-color: rgba(179, 247, 60, 0.1);
      border-radius: 12rpx;
      border-left: 6rpx solid #B3F73C;
      
      .tn-icon-info {
        color: #B3F73C;
        font-size: 32rpx;
        margin-right: 10rpx;
      }
      
      .tip-text {
        color: rgba(255, 255, 255, 0.9);
        font-size: 24rpx;
        line-height: 1.4;
      }
    }
    
    .action-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #FFFFFF;
      font-size: 26rpx;
      font-weight: bold;
      margin-bottom: 20rpx;

      .title-left {
        display: flex;
        align-items: center;

        .tn-icon-upload {
          color: #B3F73C;
          margin-right: 12rpx;
          font-size: 28rpx;
        }
      }

      .audit-status {
        .audit-text {
          padding: 6rpx 16rpx;
          border-radius: 16rpx;
          font-size: 22rpx;
          font-weight: normal;
          background: linear-gradient(135deg, rgba(255, 193, 7, 0.3), rgba(255, 193, 7, 0.1));
          color: #FFC107;
          border: 1px solid rgba(255, 193, 7, 0.3);
          box-shadow: 0 2rpx 8rpx rgba(255, 193, 7, 0.2);
        }
      }
    }
    
    .upload-area {
      margin-bottom: 24rpx;
      position: relative;
      border-radius: 16rpx;
      overflow: hidden;

      .screenshot {
        width: 100%;
        height: 320rpx;
        border-radius: 16rpx;
        object-fit: cover;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.3);
      }

      .upload-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 320rpx;
        background: linear-gradient(135deg, rgba(179, 247, 60, 0.1), rgba(255, 255, 255, 0.05));
        border: 2rpx dashed rgba(179, 247, 60, 0.4);
        border-radius: 16rpx;
        color: rgba(255, 255, 255, 0.7);
        transition: all 0.3s ease;

        &:active {
          background: linear-gradient(135deg, rgba(179, 247, 60, 0.15), rgba(255, 255, 255, 0.08));
          border-color: rgba(179, 247, 60, 0.6);
        }

        .tn-icon-add {
          font-size: 64rpx;
          margin-bottom: 12rpx;
          color: #B3F73C;
        }

        text {
          font-size: 26rpx;
          font-weight: 500;
        }
      }

      .upload-progress {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.7);
        padding: 10rpx;
        border-radius: 0 0 12rpx 12rpx;

        .progress-bar {
          width: 100%;
          height: 6rpx;
          background-color: rgba(255, 255, 255, 0.3);
          border-radius: 3rpx;
          overflow: hidden;
          margin-bottom: 5rpx;

          .progress-fill {
            height: 100%;
            background-color: #B3F73C;
            transition: width 0.3s ease;
          }
        }

        .progress-text {
          color: #FFFFFF;
          font-size: 20rpx;
          text-align: center;
          display: block;
        }
      }
    }
    

    
    .button-area {
      display: flex;
      gap: 16rpx;

      .reupload-btn, .submit-btn {
        height: 70rpx;
        line-height: 70rpx;
        border-radius: 35rpx;
        font-size: 26rpx;
        font-weight: bold;
        flex: 1;
        transition: all 0.3s ease;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
      }

      .single-btn {
        width: 100% !important;
        flex: none;
      }

      .reupload-btn {
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.08));
        color: #FFFFFF;
        border: 1px solid rgba(255, 255, 255, 0.3);
        backdrop-filter: blur(10rpx);

        &:active {
          background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
          transform: translateY(2rpx);
        }

        &:disabled {
          background: linear-gradient(135deg, rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0.02));
          color: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.1);
          box-shadow: none;
        }
      }

      .submit-btn {
        background: linear-gradient(135deg, #B3F73C, #9AE234);
        color: #000000;
        border: none;

        &:active {
          background: linear-gradient(135deg, #9AE234, #8BC34A);
          transform: translateY(2rpx);
        }

        &:disabled {
          background: linear-gradient(135deg, rgba(179, 247, 60, 0.3), rgba(154, 226, 52, 0.3));
          color: rgba(0, 0, 0, 0.4);
          box-shadow: none;
        }
      }
    }
  }
  
  /* 队伍成员提示样式 */
  .member-upload-tip {
    background: linear-gradient(135deg, rgba(255, 193, 7, 0.1), rgba(255, 152, 0, 0.05));
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 24rpx;
    border: 1px solid rgba(255, 193, 7, 0.2);
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 2rpx;
      background: linear-gradient(90deg, transparent, #FFC107, transparent);
    }

    .tip-content {
      display: flex;
      align-items: center;
      color: rgba(255, 255, 255, 0.9);
      font-size: 26rpx;

      .tn-icon-info {
        color: #FFC107;
        margin-right: 12rpx;
        font-size: 28rpx;
      }

      .tip-text {
        line-height: 1.4;
        font-weight: 500;
      }
    }
  }

  .record-rated {
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 12rpx;
    padding: 20rpx;
    
    .rated-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16rpx;
      color: #FFFFFF;
      font-size: 26rpx;
      font-weight: bold;

      .rank-result {
        .result-text {
          padding: 6rpx 16rpx;
          border-radius: 16rpx;
          font-size: 22rpx;
          font-weight: bold;

          &.win {
            background-color: rgba(76, 175, 80, 0.2);
            color: #4CAF50;
          }

          &.lose {
            background-color: rgba(244, 67, 54, 0.2);
            color: #F44336;
          }

          &.audit {
            background: linear-gradient(135deg, #FFC107, #FF8F00);
            color: #FFFFFF;
            box-shadow: 0 2rpx 8rpx rgba(255, 193, 7, 0.2);
          }
        }

        &.unknown .result-text {
          background-color: rgba(255, 193, 7, 0.2);
          color: #FFC107;
        }
      }
    }
    
    .rated-content {
      .rated-screenshot {
        margin-bottom: 10rpx;
        
        .screenshot {
          width: 100%;
          height: 200rpx;
          border-radius: 12rpx;
          object-fit: cover;
        }
      }
      

    }
  }
}
</style> 